﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace TouristAgencyDataLayer
{
    public class Boards
    {
        public static void CreateBoard(string boa)
        {
            if (!string.IsNullOrEmpty(boa))
            {
                TouristAgencyDataClassesDataContext context = new TouristAgencyDataClassesDataContext();

                Board b = new Board()
                {
                    BoardType = boa
                };

                context.Boards.InsertOnSubmit(b);
                context.SubmitChanges();
            }
        }

        public static void UpdateBoard(int boaId, string boa)
        {
            if (!string.IsNullOrEmpty(boa))
            {
                TouristAgencyDataClassesDataContext context = new TouristAgencyDataClassesDataContext();

                var res =
                    (from b in context.Boards
                     where b.BoardId == boaId
                     select b).FirstOrDefault();

                if (res != null)
                {
                    res.BoardType = boa;
                    context.SubmitChanges();
                }
            }
        }

        public static void DeleteBoard(int boaId)
        {

            TouristAgencyDataClassesDataContext context = new TouristAgencyDataClassesDataContext();

            var boa =
                (from b in context.Boards
                 where b.BoardId == boaId
                 select b).FirstOrDefault();

            if (boa != null)
            {
                var tours =
                    from t in context.Tours
                    where t.BoardId == boaId
                    select t;

                foreach (var t in tours)
                {
                    Tours.UpdateTour(t.TourId, t.DestinationId, t.StartDate, t.EndDate, t.MeanOfTransportId, null, t.Description, t.Price);
                }

                context.Boards.DeleteOnSubmit(boa);
                context.SubmitChanges();
            }
        }

        public static IQueryable<Board> GetBoards()
        {
            TouristAgencyDataClassesDataContext context = new TouristAgencyDataClassesDataContext();

            return context.Boards;
        }

        public static Board GetBoardById(int? id)
        {
            TouristAgencyDataClassesDataContext context = new TouristAgencyDataClassesDataContext();

            var res = 
                (from b in context.Boards
                where b.BoardId == id
                select b).FirstOrDefault();

            if(res != null)
            {
                return res;
            }

            return null;
        }
    }
}

